// 分组：数组对象，按照某个属性分组
export const getGroupObject = (list, attr) => {
	const map = new Map();
	list.forEach((item, index, arr) => {
		if (!map.has(item[attr])) {
			map.set(
				item[attr],
				arr.filter(a => a[attr] == item[attr]),
			);
		}
	});
	return Object.fromEntries(Array.from(map).map(item => [item[0], item[1]]));
};

// 锚点：跳转到指定锚点位置
export const scrollToSection = id => {
	let section = document.getElementById(id);
	if (section) {
		section.scrollIntoView();
	}
};

export function diffTime(time) {
	if (!time) {
		return '-';
	}
	let now = Date.now() / 1000;
	let diff = parseInt(Math.abs(now - time));
	if (diff < 3600 * 24) {
		return Math.floor(diff / 3600) + '小时';
	} else {
		let daty = Math.floor(diff / (3600 * 24));
		let hours = Math.floor((diff - 3600 * 24 * daty) / 3600);
		return daty + '天' + hours + '小时';
	}
}
// 日期格式化
export function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null;
	}
	if (!time) return '';
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
	let date;
	if (typeof time === 'object') {
		date = time;
	} else {
		if (('' + time).length === 10) time = parseInt(time) * 1000;
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
		if (result.length > 0 && value < 10) {
			value = '0' + value;
		}
		return value || 0;
	});
	return time_str;
}
// 获取随机字母
export function randomCoding(num, type) {
	var result = [];
	let typeObj = {
		number: () => {
			for (var i = 0; i < num; i++) {
				var randNum = Math.ceil(Math.random() * 10);
				result.push(randNum);
			}
		},
		letter: () => {
			for (var i = 0; i < num; i++) {
				var ranNum = Math.ceil(Math.random() * 25);
				result.push(String.fromCharCode(65 + ranNum));
			}
		},
		numLetter: () => {
			for (var i = 0; i < num.num; i++) {
				var numItem = Math.ceil(Math.random() * 10);
				result.push(numItem);
			}
			for (var j = 0; j < num.letter; j++) {
				var ranNum = Math.ceil(Math.random() * 25);
				result.push(String.fromCharCode(65 + ranNum));
			}
		},
	};
	typeObj[type]();
	return result.join('');
}
// 获取url指定参数
export function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
}
// 深拷贝
export function deepClone(source) {
	if (!source && typeof source !== 'object') {
		throw new Error('error arguments', 'shallowClone');
	}
	const targetObj = source.constructor === Array ? [] : {};
	for (const keys in source) {
		// eslint-disable-next-line no-prototype-builtins
		if (source.hasOwnProperty(keys)) {
			if (source[keys] && typeof source[keys] === 'object') {
				targetObj[keys] = source[keys].constructor === Array ? [] : {};
				targetObj[keys] = deepClone(source[keys]);
			} else {
				targetObj[keys] = source[keys];
			}
		}
	}
	return targetObj;
}
/**
 * 下载文件(流)
 */
export function downloadNewFile(obj, name) {
	const url = window.URL.createObjectURL(new Blob([obj]));
	console.log(url);
	const link = document.createElement('a');
	link.style.display = 'none';
	link.href = url;
	// const fileName = name+"."+suffix;
	link.setAttribute('downLoad', name);
	document.body.append(link);
	link.click();
	document.body.removeChild(link);
}

/**
 *
 * @param {String} url 文件地址下载
 */
export function downloadFileUrl(url) {
	const link = document.createElement('a');
	link.setAttribute('download', '');
	link.setAttribute('href', url);
	link.click();
}

export function downloadOpenFileUrl(url) {
	window.open(url);
}

// 千分位分隔符
export function formatArea(val, type = 'en-US') {
	if (!val || isNaN(val)) return '-';
	let nf = new Intl.NumberFormat(type);
	return nf.format(val);
}

//阿拉伯数字转大写，整数转大写
export function numToCapital(num, type = '') {
	if (!num) return 0;
	const strNum = Number((num + '').replace(/[,，]*/g, '')) + ''; // 记录字符
	num = parseInt(Number(strNum)); // 转为整数，
	let capitalAr = '零一二三四五六七八九十';
	let unitAr = ['十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千'];
	if (type) {
		capitalAr = '零壹贰叁肆伍陆柒捌玖拾';
		unitAr = ['拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟']; // 单位
	}
	const resultAr = []; // 记录结果，后边json.in就可
	let index = strNum.length - 1; //记录位数
	let idx = 0; // 记录单位
	let percent = 10;
	const turnNum = (num, percent, index) => {
		const unit = num / percent;
		const capital = capitalAr[Number(strNum[index])];
		if (unit < 1) {
			resultAr.push(capital);
			// 出现11【一十一】这种情况
			if (Number(strNum[index]) === 1 && (strNum.length === 2 || strNum.length === 6 || strNum.length === 10)) {
				resultAr.pop();
			}
			return false; //结束递归
		} else {
			if (capital === '零') {
				// 万和亿单位不删除
				if (!['万', '亿'].includes(resultAr[resultAr.length - 1])) {
					resultAr.pop();
				}
				// 前面有零在删掉一个零
				if (resultAr[resultAr.length - 1] === '零') {
					resultAr.pop();
				}
			}
			resultAr.push(capital);
			// 过滤存在【零万】【零亿】这种情况
			if (['万', '亿'].includes(resultAr[resultAr.length - 2]) && capital === '零') {
				resultAr.pop();
			}
			// 过滤【1亿万】这种情况
			if (resultAr[0] === '万' && resultAr[1] === '亿') {
				resultAr.shift();
			}
			// 末尾【零】删掉
			if (resultAr[0] === '零') {
				resultAr.pop();
			}
			resultAr.push(unitAr[idx++]);
			turnNum(num, percent * 10, --index);
		}
	};
	turnNum(num, percent, index);
	return resultAr.reverse().join('');
}

//字典根据key取name
let dictObj = JSON.parse(localStorage.getItem('dataDictionary')) || [];
export function getDicName(typeName, data) {
	let target = dictObj[typeName].find(item => item.id == data);
	return target ? target.dictLabel || '-' : '-';
}

export function defaultTableData(row, column, cellValue, index) {
	return cellValue || cellValue === 0 ? cellValue : '-';
}

//判断平年润年
const isLeapYear = function (year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		return true;
	} else {
		return false;
	}
};

//计算两个日期之间 相差几年几月几日
export function monthDayDiff(startTime, endTime) {
	if (startTime >= endTime) {
		return {
			year: 0,
			month: 0,
			day: 0,
		};
	}
	let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];
	let start = new Date(startTime);
	let end = new Date(endTime);
	let year = end.getFullYear() - start.getFullYear();
	let month = end.getMonth() - start.getMonth();
	let day = end.getDate() + 1 - start.getDate();
	if (month < 0) {
		year--;
		month = end.getMonth() + (12 - start.getMonth());
	}
	if (day < 0) {
		month--;
		let isLeapYearFlag = isLeapYear(start.getFullYear());
		let index = flag.findIndex(temp => {
			return temp === start.getMonth() + 1;
		});
		let monthLength;
		if (index <= 6) {
			monthLength = 31;
		} else if (index > 6 && index <= 10) {
			monthLength = 30;
		} else {
			monthLength = isLeapYearFlag ? 29 : 28;
		}
		day = end.getDate() + (monthLength - start.getDate());
	} else {
		let isLeapYearFlag = isLeapYear(end.getFullYear());
		let index = flag.findIndex(temp => {
			return temp === end.getMonth() + 1;
		});
		let monthLength;
		if (index <= 6) {
			monthLength = 31;
		} else if (index > 6 && index <= 10) {
			monthLength = 30;
		} else {
			monthLength = isLeapYearFlag ? 29 : 28;
		}
		if (day == monthLength) {
			day = 0;
			month = month + 1;
		}
	}
	return {
		year: year,
		month: month,
		day: day,
	};
}

export function getDaysDiff(timestamp1, timestamp2) {
	if (timestamp2 > timestamp1) {
		return '';
	}
	// 一天的毫秒数
	const oneDay = 24 * 60 * 60 * 1000;

	// 将时间戳转换为日期对象
	const date1 = new Date(timestamp1);
	const date2 = new Date(timestamp2);

	// 计算两个日期对象的差值
	const diffDays = Math.round((date1 - date2) / oneDay);

	return diffDays;
}

export function getType(obj) {
	return Object.prototype.toString.call(obj);
}

export function getDictoryTxt(filedName, data) {
	let dictObj = JSON.parse(localStorage.getItem('dataDictionary')) || [];
	let list = dictObj[filedName];
	let target = list.find(item => item.dictValue == data);
	return target ? target.dictLabel : '-';
}

//除法
export function accDiv(arg1, arg2, digits) {
	if (arg1 == null || arg2 == 0) {
		return 0;
	}
	if (arg2 == null || arg2 == 0) {
		return 0;
	}
	var n1, n2;
	var r1, r2; // 小数位数
	try {
		r1 = arg1.toString().split('.')[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split('.')[1].length;
	} catch (e) {
		r2 = 0;
	}
	n1 = Number(arg1.toString().replace('.', ''));
	n2 = Number(arg2.toString().replace('.', ''));
	let result = (n1 / n2) * Math.pow(10, r2 - r1);
	if (digits) {
		result = result.toFixed(digits);
	}
	return result;
}

//乘法
export function accMul(arg1, arg2, digits) {
	if (arg1 == null || arg2 == null) {
		return null;
	}
	var n1, n2;
	var r1, r2; // 小数位数
	try {
		r1 = arg1.toString().split('.')[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split('.')[1].length;
	} catch (e) {
		r2 = 0;
	}
	n1 = Number(arg1.toString().replace('.', ''));
	n2 = Number(arg2.toString().replace('.', ''));
	let result = (n1 * n2) / Math.pow(10, r1 + r2);
	if (digits) {
		result = result.toFixed(digits);
	}
	return result;
}

//加法
export function accAdd(arg1, arg2, digits) {
	var r1, r2, m;
	try {
		r1 = arg1.toString().split('.')[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split('.')[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	let result = (arg1 * m + arg2 * m) / m;
	if (digits) {
		result = result.toFixed(digits);
	}
	return result;
}

//减法
export function accSubtr(arg1, arg2, digits) {
	var r1, r2, m, n;
	try {
		r1 = arg1.toString().split('.')[1].length;
	} catch (e) {
		r1 = 0;
	}
	try {
		r2 = arg2.toString().split('.')[1].length;
	} catch (e) {
		r2 = 0;
	}
	m = Math.pow(10, Math.max(r1, r2));
	n = r1 >= r2 ? r1 : r2;
	let result = Number(((arg1 * m - arg2 * m) / m).toFixed(n));
	if (digits) {
		result = result.toFixed(digits);
	}
	return result;
}

export function guid() {
	return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = (Math.random() * 16) | 0,
			v = c == 'x' ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
}
